package com.rovinj_server.fragment;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBar;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.rovinj_server.R;
import com.rovinj_server.adapter.FragmentRecordAdapter;
import com.rovinj_server.adapter.PeopleRecyclerAdapter;
import com.rovinj_server.db.DBManager;
import com.rovinj_server.entity.InventorySub;
import com.rovinj_server.entity.InventoryTaskSub;
import com.rovinj_server.entity.People;
import com.rovinj_server.ui.SameActivity;
import com.rovinj_server.utisl.Directory;
import com.rovinj_server.utisl.ExcelUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import jxl.write.WriteException;

/**
 * Created by Administrator on 2017/5/11.
 */

public class FragmentRecordText extends Fragment {

    public Context mContext;
    @Bind(R.id.list_view)
    ListView mListView;
    @Bind(R.id.butt_quan_bu)
    Button mButtQuanBu;
    @Bind(R.id.but_tiao_jiao)
    Button mButTiaoJiao;
    @Bind(R.id.but_dao)
    Button mButDao;
    @Bind(R.id.et_search)
    EditText mEtSearch;
    private View mView;
    private int mId;
    private DBManager mDbManager;
    private static final String TAG = "---FragmentRecord";
    private List<InventorySub> mSubList = new ArrayList<>();
    private FragmentRecordAdapter mAdapter;
    private ProgressDialog mProgressDialog;
    private List<InventorySub> mListData = new ArrayList<>();
    private PopupWindow mPopupWindow;
    private List<InventoryTaskSub> mSubListXiang;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.mContext = getActivity();

    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (mView == null) {
            mView = View.inflate(mContext, R.layout.fragment_record, null);
        }
        ButterKnife.bind(this, mView);
        Bundle arguments = getArguments();
        if (arguments != null) {
            mId = arguments.getInt("id");
        }
        init();
        // initData();
        initView();

        return mView;
    }

    private void init() {
        mDbManager = new DBManager(mContext);
        mDbManager.copyDBFile();
        mListData = mDbManager.findStateSubDataList((mId + ""), "已盘", 0, 30);
        mAdapter = new FragmentRecordAdapter(mContext, mListData);
        mListView.setAdapter(mAdapter);
        mAdapter.notifyDataSetChanged();

    }

    @Override
    public void onStart() {
        super.onStart();


    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @OnClick({R.id.butt_quan_bu, R.id.but_tiao_jiao, R.id.but_dao, R.id.search_lmag})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.butt_quan_bu:  //查询
                mProgressDialog = ProgressDialog.show(mContext, "", "正在查询数据请稍等");
                mProgressDialog.setCancelable(false);
                mProgressDialog.setIndeterminate(true);
                mProgressDialog.show();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        initData();
                    }
                }).start();

                break;
            case R.id.but_dao:

                mProgressDialog = ProgressDialog.show(mContext, "", "正在查询数据请稍等");
                mProgressDialog.setCancelable(false);
                mProgressDialog.setIndeterminate(true);
                mProgressDialog.show();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        daoChu();
                    }
                }).start();


                break;
            case R.id.but_tiao_jiao:
                dialog();

                break;
            case R.id.search_lmag:
                if (mEtSearch.getText().toString() == null) {

                } else {
                    ui_Updata("查询");
                }

                break;
        }
    }

    private void ui_Updata(String str) {

        if (str.equals("查询")) {
            mListData.clear();
            //mEtSearch.getText().toString();
        }else if(str.equals("提交")) {
            mListData.clear();
            mAdapter.setListDataBean(mListData);
            mAdapter.notifyDataSetChanged();
            return;
        }
    }

    private void daoChu() {
        mSubListXiang = mDbManager.findTaskSubListXiang();
        mProgressDialog.dismiss();
        if (mSubListXiang != null && mSubListXiang.size() > 0) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Intent intent = new Intent(getActivity(), SameActivity.class);
                    startActivity(intent);
                }
            });
        } else {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    export();
                }
            });

        }

    }

    public void select_cancel(View view) {
        mPopupWindow.dismiss();
    }

    /**
     * 重复信息展示
     **/
    private void popup() {
        LayoutInflater inflater = LayoutInflater.from(getActivity());
        View view = inflater.inflate(R.layout.demand_popup_select, null, true);
        mPopupWindow = new PopupWindow(view, ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.WRAP_CONTENT, true);
        mPopupWindow.setAnimationStyle(R.style.popup_window);
        mPopupWindow.setContentView(view);
        // popupWindow.setBackgroundDrawable(new BitmapDrawable());
        mPopupWindow.setOutsideTouchable(true);
    /*    popupWindow.setTouchable(true);
        popupWindow.setFocusable(true);*/
        WindowManager.LayoutParams params = getActivity().getWindow().getAttributes();//创建当前界面的一个参数对象
        params.alpha = 0.8f;
        getActivity().getWindow().setAttributes(params);//把该参数对象设置进当前界面中
        mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                WindowManager.LayoutParams params = getActivity().getWindow().getAttributes();
                params.alpha = 1.0f;//设置为不透明，即恢复原来的界面
                getActivity().getWindow().setAttributes(params);
            }
        });

        //第一个参数为父View对象，即PopupWindow所在的父控件对象，第二个参数为它的重心，后面两个分别为x轴和y轴的偏移量
        mPopupWindow.showAtLocation(inflater.inflate(R.layout.fragment_record, null), Gravity.CENTER, 0, 0);
    }

    /**
     * 弹出对话框提示是否确定要重扫
     */
    private void dialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setMessage("提交任务吗？");
        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                mProgressDialog = ProgressDialog.show(mContext, "", "正在提交数据请稍等");
                mProgressDialog.setCancelable(false);
                mProgressDialog.setIndeterminate(true);
                mProgressDialog.show();
                // new MyThread().start();
                List<InventorySub> stateSubDataList = mDbManager.findStateSubDataList("已盘");
                if (stateSubDataList != null && stateSubDataList.size() > 0) {
                    mDbManager.insertTsakSubData(stateSubDataList); //提交已盘数据
                    //修改状态
                    for (int i = 0; i < stateSubDataList.size(); i++) {
                        String barode = stateSubDataList.get(i).getBarode();
                        mDbManager.updateState(barode, "已提交");
                    }
                    ui_Updata("提交");
                } else {
                    set_Toast("暂无扫描数据");
                }
                mProgressDialog.dismiss();
                dialog.dismiss();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.create().show();
    }

    private void initData() {
        mListData.clear();
        mListData = mDbManager.findStateSubDataList("已盘", 0, 30);
        mAdapter.setListDataBean(mListData);
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mAdapter.notifyDataSetChanged();
                mProgressDialog.dismiss();
            }
        });

        mProgressDialog.dismiss();
    }

    private PeopleRecyclerAdapter peopleRecyclerAdapter;

    private void export() {

        final ProgressDialog progressDialog = ProgressDialog.show(mContext, "", "正在导出数据请稍等");
        progressDialog.setCancelable(false);
        progressDialog.setIndeterminate(true);
        progressDialog.show();
        new AsyncTask<Void, Void, String>() {
            @Override
            protected String doInBackground(Void... params) {
                File file = Directory.getExcelFile();
                try {
                    List<InventoryTaskSub> subDataList = mDbManager.findTaskSubList();
                    peopleRecyclerAdapter = new PeopleRecyclerAdapter();
              /*      peopleRecyclerAdapter.add(new People("库位", "条码", "款式","实际数", "多于", "差异"));
                    for (int i = 0; i < subDataList.size(); i++) {
                        peopleRecyclerAdapter.add(new People
                                ((subDataList.get(i).getLocation()), (subDataList.get(i).getBarode()), (subDataList.get(i).getCode()), (subDataList.get(i).getDiscNumber() + ""), (subDataList.get(i).getMoreThan() + ""), (subDataList.get(i).getLessThan() + "")));
                    }*/
                    ExcelUtils.write(file, peopleRecyclerAdapter.getPeoples());
                } catch (final IOException e) {
                    e.printStackTrace();

                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(mContext, "Error : " + e.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    });


                    return null;
                } catch (final WriteException e) {
                    e.printStackTrace();
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(mContext, "Error : " + e.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    });
                    return null;
                }
                return file.getAbsolutePath();
            }

            @Override
            protected void onPostExecute(String path) {
                progressDialog.dismiss();
                if (TextUtils.isEmpty(path))
                    Toast.makeText(mContext, "Gagal mengekspor", Toast.LENGTH_SHORT).show();
                else
                    Toast.makeText(mContext, "Berhasil mengekspor" + path, Toast.LENGTH_SHORT).show();
            }
        }.execute();
    }


    private void initView() {
        mListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int i) {
                if (absListView.getLastVisiblePosition() == absListView.getCount() - 1 &&
                        i == SCROLL_STATE_IDLE) {
                    ProgressDialog progressDialog = ProgressDialog.show(mContext, "", "正在导出数据请稍等");
                    progressDialog.setCancelable(false);
                    progressDialog.setIndeterminate(true);
                    progressDialog.show();
                    if (mListData.size() > mAdapter.showCount) {
                        List<InventorySub> stateSubDataList = mDbManager.findStateSubDataList((mId + ""), "已盘", mListData.size(), mListData.size() + 20);
                        for (int j = 0; j < stateSubDataList.size(); j++) {
                            mListData.add(stateSubDataList.get(j));
                        }
                        mAdapter.showCount += 20;
                        mAdapter.setListDataBean(mListData);
                        mAdapter.notifyDataSetChanged();
                    }

                    progressDialog.dismiss();
                }
            }

            @Override
            public void onScroll(AbsListView absListView, int i, int i1, int i2) {
            }
        });
    }


    String buffer = "";

    class MyThread extends Thread {

        @Override
        public void run() {
            // 定义消息
            List<InventorySub> stateSubDataList = mDbManager.findStateSubDataList((mId + ""), "已盘");
            Map map = new HashMap();
            map.put("stateSubDataList", stateSubDataList);
            final String postData = JSON.toJSONString(map);
            final String str = postData;
            Log.d(TAG, "盘点已盘" + str);
            Message msg = new Message();
            msg.what = 1;
            Bundle bundle = new Bundle();
            bundle.clear();
            try {
                SharedPreferences sp = mContext.getSharedPreferences("FWDID", Context.MODE_PRIVATE);
                if (sp != null) {
                    String id = sp.getString("id", "");
                    // 连接服务器 并设置连接超时为5秒
                    Socket socket = new Socket();
                    socket.connect(new InetSocketAddress(id, 30000), 1000);
                    // 获取输入输出流
                    BufferedReader bff = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    // 读取发来服务器信息
                    String line = null;
                    buffer = "";
                    while ((line = bff.readLine()) != null) {
                        buffer = line + buffer;
                    }
                    OutputStream ou = socket.getOutputStream();
                    // 向服务器发送信息
                    ou.write(str.getBytes("UTF-8"));
                    ou.flush();
                    bundle.putString("msg", buffer.toString());
                    msg.setData(bundle);
                    //  发送消息 修改UI线程中的组件
                    myHandler.sendMessage(msg);
                    // 关闭各种输入输出流
                    bff.close();
                    ou.close();
                    socket.close();
                }
            } catch (SocketTimeoutException aa) {
                // 连接超时 在UI界面显示消息
                bundle.putString("msg", "失败=======");
                msg.setData(bundle);
                // 发送消息 修改UI线程中的组件
                myHandler.sendMessage(msg);
            } catch (IOException e) {
                // 连接超时 在UI界面显示消息
                bundle.putString("msg", "连接服务器超时，请查看网络与服务器是否开启");
                msg.setData(bundle);
                // 发送消息 修改UI线程中的组件
                myHandler.sendMessage(msg);
            }
        }
    }

    public Handler myHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {

            switch (msg.what) {
                case 0:
                    String obj = (String) msg.obj;
                   ui_Updata(obj);
                    break;

                case 1:
                    mProgressDialog.dismiss();
                    Bundle bundle = msg.getData();
                    String mMStr = bundle.getString("msg");
                    Toast.makeText(mContext, "" + mMStr, Toast.LENGTH_SHORT).show();
                    Log.d(TAG, " 服务返回信息" + mMStr);
                    break;
            }
        }
    };


    public void set_Toast(final String m_Toast) {
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(mContext, "" + m_Toast, Toast.LENGTH_SHORT).show();
            }
        });
    }



   public void  set_Message(int i,String obj){
        Message message = new Message();
       message.what=i;
       message.obj=obj;
       myHandler.sendMessage(message);
    }
}
